package dao

import (
	"github.com/astaxie/beego/orm"
	"xiaoercaidan/publicResources/models"
	"errors"
	"github.com/astaxie/beego/validation"
	"log"
	"fmt"
)

func InserRole(role *models.Role) (error) {

	o := orm.NewOrm()

	_id, err := o.Insert(role)

	role.Id = _id

	return err
}

func DeleteRole(role *models.Role) (error) {

	o := orm.NewOrm()

	_, err := o.Delete(role)

	return err
}

func InserUser(user *models.User) (error) {

	o := orm.NewOrm()
	err := o.Begin()

	_id, err := o.Insert(user)

	user.Id = _id

	fmt.Println(err)
	return err

	//if err == nil {
	//
	//	_, err := o.Raw("INSERT INTO role (user_id,role_id) VALUE  (?,?) ON DUPLICATE KEY UPDATE user_id= ?,role_id=?", user.Id, user.Role.Id, user.Id, user.Role.Id).Exec()
	//
	//	if err == nil {
	//
	//		err = o.Commit()
	//
	//		return nil
	//	} else {
	//		err = o.Rollback()
	//		return err
	//	}
	//
	//} else {
	//	o.Rollback()
	//	return err
	//}

}

func checkUser(u *models.User) (err error) {
	valid := validation.Validation{}
	b, _ := valid.Valid(&u)
	if !b {
		for _, err := range valid.Errors {
			log.Println(err.Key, err.Message)
			return errors.New(err.Message)
		}
	}
	return nil
}

func UpdateUser(user *models.User) (error) {
	o := orm.NewOrm()

	_, err := o.QueryTable("user").Filter("id", user.Id).Update(orm.Params{
		"user_name": user.UserName,
		"pass_word": user.PassWord,
		"nick_name": user.NickName,
		"email": user.Email,
		"remark": user.Remark,
		"status": user.Status,
		"last_login_time": user.LastLoginTime,
		"phone": user.Phone,
		"address": user.Address,
		"image": user.Image,
		"birth": user.Birth,

	})

	return err
}

func QeryUserBlur(params map[string]string) (*[]models.User) {

	o := orm.NewOrm()

	var users []models.User

	var qs orm.QuerySeter

	qs = o.QueryTable("user")

	for k, v := range params {
		qs = qs.Filter(k + "__icontains", v)
	}

	qs.RelatedSel().All(&users)

	//for _, v := range users {
	//	_, _ = orm.NewOrm().LoadRelated(v, "role")
	//
	//}

	if (len(users) > 0) {
		return &users
	} else {
		return nil
	}

}

func QeryRole() (*[]models.Role) {

	o := orm.NewOrm()

	var roles []models.Role

	o.QueryTable("role").All(&roles)

	if (len(roles) > 0) {
		return &roles
	} else {
		return nil
	}

}

func QeryUser(params map[string]string) (*models.User) {

	o := orm.NewOrm()

	var user models.User

	var qs orm.QuerySeter

	qs = o.QueryTable("user")

	for k, v := range params {
		qs = qs.Filter(k + "__exact", v)
	}

	qs.RelatedSel().One(&user)

	//for index, _ := range users {
	//	orm.NewOrm().LoadRelated(users[index], "Role")
	//}

	return &user

}

func DeleteUsers(ids string) (error) {

	o := orm.NewOrm()

	_, err := o.Raw("delete from user where id in(?)", ids).Exec()

	if err == nil {
		return nil
	} else {
		return err
	}
}
